package api

import (
	"net/http"

	"example.com/rest/example/dao"
	"example.com/rest/example/model"

	"github.com/gin-gonic/gin"
	"github.com/guregu/null"
	"github.com/julienschmidt/httprouter"
)

var (
	_ = null.Bool{}
)

func configAlbumsRouter(router *httprouter.Router) {
	router.GET("/albums", GetAllAlbums)
	router.POST("/albums", AddAlbums)
	router.GET("/albums/:argAlbumID", GetAlbums)
	router.PUT("/albums/:argAlbumID", UpdateAlbums)
	router.DELETE("/albums/:argAlbumID", DeleteAlbums)
}

func configGinAlbumsRouter(router gin.IRoutes) {
	router.GET("/albums", ConverHttprouterToGin(GetAllAlbums))
	router.POST("/albums", ConverHttprouterToGin(AddAlbums))
	router.GET("/albums/:argAlbumID", ConverHttprouterToGin(GetAlbums))
	router.PUT("/albums/:argAlbumID", ConverHttprouterToGin(UpdateAlbums))
	router.DELETE("/albums/:argAlbumID", ConverHttprouterToGin(DeleteAlbums))
}

// GetAllAlbums is a function to get a slice of record(s) from albums table in the main database
// @Summary Get list of Albums
// @Tags Albums
// @Description GetAllAlbums is a handler to get a slice of record(s) from albums table in the main database
// @Accept  json
// @Produce  json
// @Param   page     query    int     false        "page requested (defaults to 0)"
// @Param   pagesize query    int     false        "number of records in a page  (defaults to 20)"
// @Param   order    query    string  false        "db sort order column"
// @Success 200 {object} api.PagedResults{data=[]model.Albums}
// @Failure 400 {object} api.HTTPError
// @Failure 404 {object} api.HTTPError
// @Router /albums [get]
// http "http://localhost:8080/albums?page=0&pagesize=20" X-Api-User:user123
func GetAllAlbums(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	ctx := initializeContext(r)
	page, err := readInt(r, "page", 0)
	if err != nil || page < 0 {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	pagesize, err := readInt(r, "pagesize", 20)
	if err != nil || pagesize <= 0 {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	order := r.FormValue("order")

	if err := ValidateRequest(ctx, r, "albums", model.RetrieveMany); err != nil {
		returnError(ctx, w, r, err)
		return
	}

	records, totalRows, err := dao.GetAllAlbums(ctx, page, pagesize, order)
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	result := &PagedResults{Page: page, PageSize: pagesize, Data: records, TotalRecords: totalRows}
	writeJSON(ctx, w, result)
}

// GetAlbums is a function to get a single record from the albums table in the main database
// @Summary Get record from table Albums by  argAlbumID
// @Tags Albums
// @ID argAlbumID
// @Description GetAlbums is a function to get a single record from the albums table in the main database
// @Accept  json
// @Produce  json
// @Param  argAlbumID path int true "AlbumId"
// @Success 200 {object} model.Albums
// @Failure 400 {object} api.HTTPError
// @Failure 404 {object} api.HTTPError "ErrNotFound, db record for id not found - returns NotFound HTTP 404 not found error"
// @Router /albums/{argAlbumID} [get]
// http "http://localhost:8080/albums/1" X-Api-User:user123
func GetAlbums(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	ctx := initializeContext(r)

	argAlbumID, err := parseInt32(ps, "argAlbumID")
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	if err := ValidateRequest(ctx, r, "albums", model.RetrieveOne); err != nil {
		returnError(ctx, w, r, err)
		return
	}

	record, err := dao.GetAlbums(ctx, argAlbumID)
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	writeJSON(ctx, w, record)
}

// AddAlbums add to add a single record to albums table in the main database
// @Summary Add an record to albums table
// @Description add to add a single record to albums table in the main database
// @Tags Albums
// @Accept  json
// @Produce  json
// @Param Albums body model.Albums true "Add Albums"
// @Success 200 {object} model.Albums
// @Failure 400 {object} api.HTTPError
// @Failure 404 {object} api.HTTPError
// @Router /albums [post]
// echo '{"album_id": 2,"title": "VuOCQtvXOhcXlAjielByECpod","artist_id": 98}' | http POST "http://localhost:8080/albums" X-Api-User:user123
func AddAlbums(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	ctx := initializeContext(r)
	albums := &model.Albums{}

	if err := readJSON(r, albums); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	if err := albums.BeforeSave(); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
	}

	albums.Prepare()

	if err := albums.Validate(model.Create); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	if err := ValidateRequest(ctx, r, "albums", model.Create); err != nil {
		returnError(ctx, w, r, err)
		return
	}

	var err error
	albums, _, err = dao.AddAlbums(ctx, albums)
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	writeJSON(ctx, w, albums)
}

// UpdateAlbums Update a single record from albums table in the main database
// @Summary Update an record in table albums
// @Description Update a single record from albums table in the main database
// @Tags Albums
// @Accept  json
// @Produce  json
// @Param  argAlbumID path int true "AlbumId"
// @Param  Albums body model.Albums true "Update Albums record"
// @Success 200 {object} model.Albums
// @Failure 400 {object} api.HTTPError
// @Failure 404 {object} api.HTTPError
// @Router /albums/{argAlbumID} [put]
// echo '{"album_id": 2,"title": "VuOCQtvXOhcXlAjielByECpod","artist_id": 98}' | http PUT "http://localhost:8080/albums/1"  X-Api-User:user123
func UpdateAlbums(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	ctx := initializeContext(r)

	argAlbumID, err := parseInt32(ps, "argAlbumID")
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	albums := &model.Albums{}
	if err := readJSON(r, albums); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	if err := albums.BeforeSave(); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
	}

	albums.Prepare()

	if err := albums.Validate(model.Update); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	if err := ValidateRequest(ctx, r, "albums", model.Update); err != nil {
		returnError(ctx, w, r, err)
		return
	}

	albums, _, err = dao.UpdateAlbums(ctx,
		argAlbumID,
		albums)
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	writeJSON(ctx, w, albums)
}

// DeleteAlbums Delete a single record from albums table in the main database
// @Summary Delete a record from albums
// @Description Delete a single record from albums table in the main database
// @Tags Albums
// @Accept  json
// @Produce  json
// @Param  argAlbumID path int true "AlbumId"
// @Success 204 {object} model.Albums
// @Failure 400 {object} api.HTTPError
// @Failure 500 {object} api.HTTPError
// @Router /albums/{argAlbumID} [delete]
// http DELETE "http://localhost:8080/albums/1" X-Api-User:user123
func DeleteAlbums(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	ctx := initializeContext(r)

	argAlbumID, err := parseInt32(ps, "argAlbumID")
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	if err := ValidateRequest(ctx, r, "albums", model.Delete); err != nil {
		returnError(ctx, w, r, err)
		return
	}

	rowsAffected, err := dao.DeleteAlbums(ctx, argAlbumID)
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	writeRowsAffected(w, rowsAffected)
}
